package com.edu.edu.day9_19_week7_homework.thread;

import android.os.AsyncTask;

import com.edu.edu.day9_19_week7_homework.bean.TopTitles;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 9/20 0020.
 */
public class LoadTitleJsonTask extends AsyncTask<String,Void,List<TopTitles>>{

    public interface onGetJsonTitleResult{
        void onGetTitleResult(List<TopTitles> topTitles);
    }
    private onGetJsonTitleResult mListener;

    public LoadTitleJsonTask(onGetJsonTitleResult listener){
        this.mListener = listener;
    }

    @Override
    protected List<TopTitles> doInBackground(String... strings) {
        byte[] bytes = HttpUtil.loadData(strings[0]);
        String json = new String(bytes);
        List<TopTitles> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                String id = String.valueOf(obj.getInt("id"));
                String name=obj.getString("name");
                TopTitles topTitles = new TopTitles(id,name);
                list.add(topTitles);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    //回调标题
    @Override
    protected void onPostExecute(List<TopTitles> result) {
        super.onPostExecute(result);
        if(mListener != null && result != null){
            mListener.onGetTitleResult(result);
        }
    }
}
